package com.jilian.mydemo.modul.order.ui;

import android.Manifest;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.contrarywind.view.WheelView;
import com.jilian.mydemo.MyApplication;
import com.jilian.mydemo.R;
import com.jilian.mydemo.base.BaseActivity;
import com.jilian.mydemo.base.BaseDto;
import com.jilian.mydemo.common.dto.FinishImgDto;
import com.jilian.mydemo.common.dto.OrderDetailDto;
import com.jilian.mydemo.common.dto.OrderDto;
import com.jilian.mydemo.common.dto.PathDto;
import com.jilian.mydemo.dialog.nicedialog.BaseNiceDialog;
import com.jilian.mydemo.dialog.nicedialog.NiceDialog;
import com.jilian.mydemo.dialog.nicedialog.ViewConvertListener;
import com.jilian.mydemo.dialog.nicedialog.ViewHolder;
import com.jilian.mydemo.listener.CustomItemClickListener;
import com.jilian.mydemo.modul.order.adapter.SignUpAdapter;
import com.jilian.mydemo.modul.order.adapter.WheelAdapter;
import com.jilian.mydemo.modul.order.viewmodel.OrderViewModel;
import com.jilian.mydemo.utils.DisplayUtil;
import com.jilian.mydemo.utils.EmptyUtils;
import com.jilian.mydemo.utils.PermissionsObserver;
import com.jilian.mydemo.utils.ToastUitl;
import com.jilian.mydemo.utils.TwoPointLengthFilter;
import com.jilian.mydemo.utils.selectphoto.SelectPhotoUtils;
import com.jilian.mydemo.views.RecyclerViewSpacesItemDecoration;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.jilian.mydemo.Constant.FINALVALUE.FILE_PROVIDER;

public class FinishOrderActivity extends BaseActivity implements CustomItemClickListener, SignUpAdapter.CloseListener {

    private RecyclerView rvTwo;
    private SignUpAdapter adapter;
    private List<PathDto> datas;
    private GridLayoutManager gridLayoutManager;
    private List<String> list;
    private TextView tvAddService;
    private List<String> serviceList;
    private OrderDto orderDto;
    private TextView tvNumber;
    private TextView tvType;
    private TextView tvName;
    private TextView tvDate;
    private TextView tvAdress;
    private LinearLayoutManager linearLayoutManager;
    private OrderViewModel viewModel;
    private TextView tvOk;
    private EditText etChargemoney;
    private EditText etReducemoney;
    private EditText etRemark;
    private OrderDetailDto orderDetailDto;
    private TextView etStander;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.removeActivity(this);
    }

    @Override
    protected void createViewModel() {
        viewModel = ViewModelProviders.of(this).get(OrderViewModel.class);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_finishorder;
    }

    @Override
    public void initView() {
        setNormalTitle("订单完成", v -> finish());
        etStander = (TextView) findViewById(R.id.et_stander);
        tvOk = (TextView) findViewById(R.id.tv_ok);
        rvTwo = (RecyclerView) findViewById(R.id.rv_two);
        tvAddService = (TextView) findViewById(R.id.tv_add_service);
        tvNumber = (TextView) findViewById(R.id.tv_number);
        tvType = (TextView) findViewById(R.id.tv_type);
        tvName = (TextView) findViewById(R.id.tv_name);
        tvDate = (TextView) findViewById(R.id.tv_date);
        tvAdress = (TextView) findViewById(R.id.tv_adress);
        etChargemoney = (EditText) findViewById(R.id.et_chargemoney);
        //只能 输入两位小数
        etChargemoney.setFilters(new InputFilter[]{new TwoPointLengthFilter()});

        etReducemoney = (EditText) findViewById(R.id.et_reducemoney);
        etRemark = (EditText) findViewById(R.id.et_remark);
        HashMap<String, Integer> map = new HashMap<>();
        map.put(RecyclerViewSpacesItemDecoration.BOTTOM_DECORATION, DisplayUtil.dip2px(this, 10));//下间距
        rvTwo.addItemDecoration(new RecyclerViewSpacesItemDecoration(map));
        gridLayoutManager = new GridLayoutManager(this, 3);
        rvTwo.setLayoutManager(gridLayoutManager);
        datas = new ArrayList<>();
        PathDto dto = new PathDto();
        dto.setType(1);
        datas.add(dto);
        adapter = new SignUpAdapter(this, datas, this, this);
        rvTwo.setAdapter(adapter);
        list = new ArrayList<>();
        list.add("");
        serviceList = new ArrayList<>();


    }

    @Override
    public void initData() {
        orderDto = (OrderDto) getIntent().getSerializableExtra("order");
        orderDetailDto = (OrderDetailDto) getIntent().getSerializableExtra("orderDetailDto");

        if (EmptyUtils.isNotEmpty(orderDto)) {
            tvNumber.setText(orderDto.getOrderNo());
            tvType.setText(orderDto.getServiceType());
            tvName.setText(orderDto.getCustomerName());
            tvDate.setText(orderDto.getBookTime());
            tvAdress.setText(orderDto.getServiceAddress());
        }
        if (EmptyUtils.isNotEmpty(orderDetailDto)) {
            //服务费标准
            etStander.setText(orderDetailDto.getServiceStandard());
            //挂账费
            etChargemoney.setText(orderDetailDto.getPendingMoney() == null ? "0.00" : (orderDetailDto.getPendingMoney().setScale(2, BigDecimal.ROUND_DOWN).toString()));
            //服务费优惠
            etReducemoney.setText(orderDetailDto.getReduceMoney());
        }

    }

    @Override
    public void initListener() {
        tvAddService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showRefundReasonDialog();
            }
        });
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!EmptyUtils.isNotEmpty(getFiles())) {
                    ToastUitl.showImageToastTips("请上传图片");
                    return;
                }
                if (TextUtils.isEmpty(etChargemoney.getText().toString())) {
                    ToastUitl.showImageToastTips("挂账费不能为空");
                    return;
                }
                uploadData();
            }
        });

    }

    private void uploadData() {
        showLoadingDialog();
        viewModel.uploadFinishImg(etChargemoney.getText().toString(), getFiles(), orderDto.getId(), etRemark.getText().toString(), etReducemoney.getText().toString());

        viewModel.getFinishImliveData().observe(this, new Observer<BaseDto<List<FinishImgDto>>>() {
            @Override
            public void onChanged(@Nullable BaseDto<List<FinishImgDto>> listBaseDto) {
                hideLoadingDialog();

                if (listBaseDto.isSuccess()) {
                    if (!EmptyUtils.isNotEmpty(listBaseDto.getData())) {
                        ToastUitl.showImageToastTips("未获取到服务产品信息");
                        return;

                    }
                    Intent intent = new Intent(FinishOrderActivity.this, InputServiceDataActivity.class);
                    intent.putExtra("data", JSONObject.toJSONString(listBaseDto.getData()));
                    intent.putExtra("orderId", orderDto.getId());
                    intent.putExtra("order", orderDto);
                    startActivity(intent);
                } else {
                    ToastUitl.showImageToastTips(listBaseDto.getMsg());
                }

            }
        });
    }

    /**
     * 获取上传照片
     *
     * @return
     */
    private List<File> getFiles() {
        List<File> files = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            if (datas.get(i).getType() == 2) {
                File file = new File(datas.get(i).getUrl());
                files.add(file);
            }


        }
        return files;
    }

    /**
     * 退单对话框
     */
    private void showRefundReasonDialog() {

        NiceDialog.init()
                .setLayoutId(R.layout.dialog_select_courier)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        dialog.setOutCancel(false);
                        WheelView wheelview = (WheelView) holder.getView(R.id.wheelview);
                        wheelview.setCyclic(false);
                        TextView tvTitle = (TextView) holder.getView(R.id.tv_title);
                        tvTitle.setText("选择服务类型");
                        TextView tvCancel = (TextView) holder.getView(R.id.tv_cancel);

                        TextView tvFinish = (TextView) holder.getView(R.id.tv_finish);
                        wheelview.setAdapter(new WheelAdapter(serviceList));

                        tvFinish.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {

                                dialog.dismiss();
                            }
                        });
                        tvCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                            }
                        });
                        wheelview.setCurrentItem(0);
                    }
                })
                .setShowBottom(true)
                .show(getSupportFragmentManager());
    }

    @Override
    public void onItemClick(View view, int position) {
        if (datas.get(position).getType() == 2) {
            seePhoto();
        } else {
            showAddPhoto();
        }


    }

    /**
     * 查看图片
     */
    private void seePhoto() {

    }

    /**
     * 添加图片
     */
    private void showAddPhoto() {
        showSelectPhotoTypeDialog();
    }

    @Override
    public void close(int position) {
        datas.remove(position);
        if (datas.get(datas.size() - 1).getType() == 2) {
            PathDto dto = new PathDto();
            dto.setType(1);
            datas.add(dto);
        }
        adapter = new SignUpAdapter(this, datas, this, this);
        rvTwo.setAdapter(adapter);
    }

    //相机
    private final int FROM_CAPTURE = 10001;
    //相册
    private final int FROM_ALBUM = 10002;

    /**
     * 选中照片
     */
    private void showSelectPhotoTypeDialog() {
        NiceDialog.init()
                .setLayoutId(R.layout.dialog_photo_select)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        dialog.setOutCancel(false);
                        Button btnTakingPictures = (Button) holder.getView(R.id.btn_taking_pictures);
                        Button btnPhotoAlbum = (Button) holder.getView(R.id.btn_photo_album);
                        Button btnCancel = (Button) holder.getView(R.id.btn_cancel);
                        btnCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                            }
                        });
                        //拍照
                        btnTakingPictures.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                                RxPermissions.getInstance(FinishOrderActivity.this).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new PermissionsObserver() {
                                    @Override
                                    protected void onGetPermissionsSuccess() {
                                        SelectPhotoUtils.fromCapture(FinishOrderActivity.this, FILE_PROVIDER, FROM_CAPTURE);
                                    }

                                    @Override
                                    protected void onGetPermissionsSuccessFailuer() {
                                        ToastUitl.showImageToastTips("相机权限被拒绝，无法使用拍照功能");
                                    }
                                });

                            }
                        });
                        //相册
                        btnPhotoAlbum.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();

                                RxPermissions.getInstance(FinishOrderActivity.this).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new PermissionsObserver() {
                                    @Override
                                    protected void onGetPermissionsSuccess() {
                                        SelectPhotoUtils.fromAlbum(FinishOrderActivity.this, FILE_PROVIDER, 10 - datas.size(), FROM_ALBUM);
                                    }

                                    @Override
                                    protected void onGetPermissionsSuccessFailuer() {
                                        ToastUitl.showImageToastTips("相机权限被拒绝，无法使用拍照功能");
                                    }
                                });

                            }

                        });

                    }
                })
                .setShowBottom(true)
                .show(getSupportFragmentManager());
    }

    private String path;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //图库
                case FROM_ALBUM:
                    List<Uri> uriList = SelectPhotoUtils.albumResult(data);
                    for (int i = 0; i < uriList.size(); i++) {
                        Uri uri = uriList.get(i);
                        path = SelectPhotoUtils.getRealPathFromURI(this, uri);
                        PathDto dto = new PathDto(path, 2);
                        datas.add(0, dto);
                        if (datas.size() == 10) {
                            datas.remove(datas.size() - 1);
                        }
                    }
                    adapter.notifyDataSetChanged();
                    break;
                //相机
                case FROM_CAPTURE:
                    path = SelectPhotoUtils.capturePathResult();
                    PathDto dto = new PathDto(path, 2);
                    datas.add(0, dto);
                    if (datas.size() == 10) {
                        datas.remove(datas.size() - 1);
                    }
                    adapter.notifyDataSetChanged();
                    break;
            }

        }
    }


}
